package org.tinygroup.springmvc.handler.impl;

import java.lang.reflect.Method;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.tinygroup.springmvc.handler.MethodInvokePreHandler;
import org.tinygroup.springmvc.handler.MethodInvokePreHandlerChain;

/**
 * 
 * 默认的MethodInvokePreHandler链
 * 
 * @author renhui
 */
public class DefaultMethodInvokePreHandlerChain implements
		MethodInvokePreHandlerChain {

	private List<MethodInvokePreHandler> methodInvokePreHandlers;

	public List<MethodInvokePreHandler> getMethodInvokePreHandlers() {
		return methodInvokePreHandlers;
	}

	public void setMethodInvokePreHandlers(
			List<MethodInvokePreHandler> methodInvokePreHandlers) {
		this.methodInvokePreHandlers = methodInvokePreHandlers;
	}

	private int currentPosition = 0;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.alipay.sofa.runtime.web.smvc.servlet.handler.MethodInvokePreHandlerChain
	 * #doPreMethodInvokeHandler(javax.servlet.http.HttpServletRequest,
	 * javax.servlet.http.HttpServletResponse, java.lang.reflect.Method,
	 * java.lang.Object)
	 */
	public void doPreMethodInvokeHandler(HttpServletRequest request,
			HttpServletResponse response, Method handlerMethod, Object handler) {

		if (methodInvokePreHandlers == null
				|| currentPosition > methodInvokePreHandlers.size()) {
			return;
		}
		if (currentPosition == methodInvokePreHandlers.size()) {
			return;
		} else {
			currentPosition++;
			MethodInvokePreHandler methodInvokePreHandler = methodInvokePreHandlers
					.get(currentPosition - 1);
			methodInvokePreHandler.doPreMethodInvokeHandler(request, response,
					handlerMethod, handler, this);
		}

	}

}